﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HelfenHelfen.DataAccess.Interfaces;

namespace HelfenHelfen.DataAccess
{
    public class MessageDataAccess : IMessageDataAccess
    {
        public void Create(Entities.Message message)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                db.Messages.AddObject(message);
                db.SaveChanges();
            }
        }

        public void Delete(Guid messageGuid)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                var msg = (from m in db.Messages
                          where m.MessageGUID == messageGuid
                          select m).FirstOrDefault();
                if (msg != null)
                {
                    db.DeleteObject(msg);
                    db.SaveChanges();
                }
            }
        }

        public IEnumerable<Entities.Message> GetMessages(Guid userGuid)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                return db.Messages.Where(m => m.RecipientUserDetailGUID == userGuid).ToList();
            }
        }

        public void SetMessageUnread(Guid messageGuid, bool unreadFlag)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                var msg = (from m in db.Messages
                          where m.MessageGUID == messageGuid
                          select m).FirstOrDefault();
                if (msg != null)
                {
                    msg.IsUnread = unreadFlag;
                    db.SaveChanges();
                }
            }
        }

        public int GetMessageCount(Guid userGuid)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                return db.Messages.Where(m => m.RecipientUserDetailGUID == userGuid
                                                && m.IsUnread).Count();
            }
        }
    }
}
